package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.dao.MenuDao;
import com.itheima.dao.PermissionDao;
import com.itheima.dao.RoleDao;
import com.itheima.dao.UserDao;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.pojo.Menu;
import com.itheima.pojo.Permission;
import com.itheima.pojo.Role;
import com.itheima.pojo.User;
import com.itheima.service.UserService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;


import java.util.*;


/**
 * 用户服务
 */
@Service(interfaceClass = UserService.class)
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Autowired
    private RoleDao roleDao;
    @Autowired
    private PermissionDao permissionDao;
    @Autowired
    private MenuDao menuDao;
    @Autowired
    private JedisPool jedisPool;

    //根据用户名查询数据库获取用户信息和关联的角色信息，同时需要查询角色关联的权限信息
    public User findByUsername(String username) {
        Jedis jedis = jedisPool.getResource();
        String userJson = jedis.get(username);
        User user;
        // redis中有数据
        if (userJson != null && userJson.length() > 0) {
            user = JSON.parseObject(userJson, User.class);
            System.out.println("redis");
            return user;
        }
        // redis中没有数据需要从mysql中查询
        user = userDao.findByUsername(username);//查询用户基本信息，不包含用户的角色
        if (user == null) {
            return null;
        }
        Integer userId = user.getId();
        //根据用户ID查询对应的角色
        Set<Role> roles = roleDao.findByUserId(userId);
        for (Role role : roles) {
            Integer roleId = role.getId();
            //根据角色ID查询关联的权限
            Set<Permission> permissions = permissionDao.findByRoleId(roleId);
            role.setPermissions(permissions);//让角色关联权限
            //根据角色ID查询关联的菜单
            LinkedHashSet<Menu> menus = menuDao.findMenusByRoleId(roleId);
            role.setMenus(menus);//让角色关联菜单
        }
        user.setRoles(roles);//让用户关联角色
        // 存入redis中
        String jsonUser = JSON.toJSONString(user);
        jedis.setex(username, 60 * 5 * 5, jsonUser);
        return user;
    }

    /**
     * 查询用户
     * currentPage: this.pagination.currentPage,//页码
     * pageSize: this.pagination.pageSize,//每页显示数
     * queryString: this.pagination.queryString//查询条件
     */
    @Override
    public PageResult pageQuery(QueryPageBean queryPageBean) {
        Integer currentPage = queryPageBean.getCurrentPage();//页码
        Integer pageSize = queryPageBean.getPageSize();//每页显示数
        String queryString = queryPageBean.getQueryString();//查询条件
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.findByQueryString(queryString);
        return new PageResult(page.getTotal(), page.getResult());
    }

    @Override
    public User findUserById(Integer id) {
        User user = userDao.findUserById(id);
        return user;
    }

    @Override
    public List<Integer> findRoleById(Integer id) {
        return userDao.findRoleById(id);
    }

    @Override
    public void editUser(Integer[] roleIds, User user) throws Exception {
        Integer userId = user.getId();
       /* Date birthday = user.getBirthday();
        String birthdayString = DateUtils.parseDate2String(birthday);
        Date date = DateUtils.parseString2Date(birthdayString);
        user.setBirthday(date);*/
        userDao.edit(user);
        userDao.deleteUserAndRoleRelation(userId);
        add_user_role(userId, roleIds);
    }

    //根据user的id跟role的id搭建t_user_role的关系
    public void add_user_role(Integer userId, Integer[] roleIds) {
        if (roleIds != null && roleIds.length > 0) {
            for (Integer roleId : roleIds) {
                Map<String, Integer> map = new HashMap<>();
                map.put("roleId", roleId);
                map.put("userId", userId);
                userDao.addUserAndRoleRelation(map);
            }
        }
    }

    @Override
    public void addUser(Integer[] roleIds, User user) {
        userDao.add(user);
        this.setUserIdAndRoleId(roleIds, user);

    }

    @Override
    public PageResult findPage(QueryPageBean queryPageBean) {
        String queryString = queryPageBean.getQueryString();
        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userDao.fingByCondition(queryString);
        List<User> result = page.getResult();
        long total = page.getTotal();
        return new PageResult(total, result);
    }

    @Override
    public void delete(Integer id) {
        userDao.deleteUserIdAndRoleId(id);
        userDao.delete(id);
    }

    public void setUserIdAndRoleId(Integer[] roleIds, User user) {
        Integer user_id = user.getId();
        for (Integer role_id : roleIds) {
            Map map = new HashMap();
            map.put("user_id", user_id);
            map.put("role_id", role_id);
            userDao.setUserIdAndRoleId(map);
        }
    }


}
